﻿
namespace EasyNet.Solr.Impl
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization.Json;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;

    public class JsonFacetQueriesParser : ISolrResponseParser<string, IList<FacetField>>
    {
        public IList<FacetField> Parse(string result)
        {
            if (result == null)
            {
                return null;
            }

            IList<FacetField> facetQueriesResult = null;
            var bytes = Encoding.UTF8.GetBytes(result);

            using (var reader = JsonReaderWriterFactory.CreateJsonReader(bytes, XmlDictionaryReaderQuotas.Max))
            {
                var xmlDoc = XDocument.Load(reader);

                var facetCounts = xmlDoc.Root.Element("facet_counts");

                if (facetCounts == null)
                {
                    return null;
                }

                var facetQueries = facetCounts.Element("facet_queries");

                if (facetQueries == null)
                {
                    return null;
                }

                facetQueriesResult = new List<FacetField>(facetQueries.Elements().Count());

                foreach (var element in facetQueries.Elements())
                {
                    facetQueriesResult.Add(new FacetField() { Name = element.Attribute("item").Value, Count = int.Parse(element.Value) });
                }
            }

            return facetQueriesResult;
        }
    }
}
